<template>
  <div id="shopping">
    <h1>购物车</h1>
    <el-table :data="tabledata" border height="400" style="width: 75%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" width="120" />
      <el-table-column prop="num" label="数量" width="210">
        <template #default="scope">
          <el-input-number v-model="scope.row.num" :min="1" @change="handleChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="money" label="小计" width="120" />

      <el-table-column prop label="操作" width="100">
        <template #default="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <span style="float: right; margin: 0px 280px;color:red">总计：￥ {{ moneys }}</span>
    <div class="divcart">
      <el-button @click="clearCartByUn1 = true">清空购物车</el-button>
      <el-dialog v-model="clearCartByUn1" title="Tips" width="30%" :before-close="handleClose">
        <span>你确定要清空购物车吗</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="clearCartByUn1 = false">取消</el-button>
            <el-button type="primary" @click="clearCartByUn()">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-button v-if="tabledata != ''" @click="dialogTableVisi()">结算</el-button>
      <!-- 订单预览 -->
      <el-dialog v-model="dialogTableVisible" title="订单预览" :before-close="handleClose">
        <el-table :data="tabledata2" height="300">
          <el-table-column property="name" label="name" width="350"></el-table-column>
          <el-table-column property="price" label="价格" width="100"></el-table-column>
          <el-table-column property="num" width="100" label="数量"></el-table-column>
          <el-table-column property="money" label="小计" width="100"></el-table-column>
        </el-table>

        <el-form :model="form">
          <el-form-item label="收货地址">
            <el-select v-model="form.region" placeholder="选择地址" @change="currentSel">
              <el-option
                v-for="tab in tabledata1"
                :key="tab.length"
                :label="tab.name + '  ' + tab.phone + '  ' + tab.detail"
                :value="tab.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-button style="margin:0 100px 0px 50px;" @click="address = true" type="primary">管理地址</el-button>
        <!-- 地址管理 -->
        <span style="float: right;color:red;font-size: 15px;">商品金额总计：￥ {{ moneys }}</span>
        <el-dialog v-model="address" title="地址管理" :before-close="handleClose">
          <!-- 查看地址 -->
          <el-table :data="tabledata1" height="300">
            <el-table-column property="name" label="name" width="150"></el-table-column>
            <el-table-column property="phone" label="电话" width="200"></el-table-column>

            <el-table-column property="detail" label="地址" width="200"></el-table-column>
            <el-table-column prop label="操作" width="100">
              <template #default="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete2(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 添加地址 -->
          <el-form
            label-width="80px"
            ref="addressfrom"
            :model="addressfrom"
            label-position="left"
            status-icon
            :rules="rules"
            style="clear: both;width:400px;margin-left:50px"
          >
            <el-form-item label="名字" prop="name">
              <el-input v-model="addressfrom.name" type></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="addressfrom.phone" type></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="detail">
              <el-input v-model="addressfrom.detail" type></el-input>
            </el-form-item>
            <el-button type="primary" @click="addaddress('addressfrom')">添加</el-button>
          </el-form>
        </el-dialog>

        <template #footer>
          <span class="dialog-footer" style="margin-top:50px">
            <el-button @click="dialogTableVisible = false">取消</el-button>
            <el-button type="primary" @click="xiadan">下单</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  toRefs,
  ref,
} from "vue";
import axios from "axios";
import { ElMessageBox, ElNotification } from "element-plus";


//购物车查询
function loattaba(state) {
  if (state.username != null) {

    axios({
      url: "/getCart",
      method: "get",
      params: {
        username: state.username
      },
    })
      .then((res) => {
        if (res.data.code == 200) {
          var u = res.data.data;
          var i = 0;
          state.tabledata = []
          state.moneys = 0
          for (i; i < u.length; i++) {
            state.moneys += u[i].money;
            state.tabledata.push(u[i]);
          }
        }
      })
      .catch((err) => {
        console.error();
      });
  }
}
//单个删除商品
function handleDelete(state) {
  const handleDelete = (index, row) => {
    axios({
      url: "/clearCart",
      method: "get",
      params: {
        username: JSON.parse(sessionStorage.getItem("token")),
        gid: row.gid,
      },
    }).then((res) => {
      if (res.data.code == 200) {

        ElNotification({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        loattaba(state)
      } else {
        ElNotification({
          title: "失败",
          message: "删除失败",
          type: "error",
          duration: 2000,
        });
      }
    });
  };
  return {
    handleDelete,
  };
}
//删除地址
function handleDelete2(state) {
  const handleDelete2 = (index, row) => {
    axios({
      url: "/userAddressDel",
      method: "get",
      params: {
        id: row.id,
      },
    }).then((res) => {
      // console.log(res.data);
      if (res.data.code == 200) {
        ElNotification({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        getorder(state)
      } else {
        ElNotification({
          title: "失败",
          message: "删除失败",
          type: "error",
          duration: 2000,
        });
      }
    });
  }
  return {
    handleDelete2
  }
}
//修改数量
function handleChange(state) {
  const handleChange = (row) => {
    axios({
      url: "/updateCartNumE",
      method: "get",
      params: {
        gid: row.gid,
        price: row.price,
        num: row.num,
        username: state.username
      },
    }).then((res) => {
      // console.log(res.data);
      if (res.data.code == 200) {
        loattaba(state)
        getorder(state)
      } else {
        ElNotification({
          title: "失败",
          message: "修改失败",
          type: "error",
          duration: 2000,
        });
      }
    });
  };
  return {
    handleChange,
  };
}
//订单预览和地址
function getorder(state) {
  if (state.username == null) {

  } else {
    axios({
      url: "/getOrderView",
      method: "get",
      params: {
        username: state.username
      },
    })
      .then((res) => {
        if (res.data.code == 200) {
          var u = res.data.data.addList;
          var i = 0;
          state.tabledata1 = []
          state.tabledata2 = []
          for (i; i < u.length; i++) {
            state.tabledata1.push(u[i]);
          }
          var z = res.data.data.cartList;
          var i = 0;
          for (i; i < z.length; i++) {
            state.tabledata2.push(z[i]);
          }
        }
      })
      .catch((err) => {
        console.error();
      });
  }
}
//清空购物车
function clearCart(state) {
  const clearCartByUn = () => {
    axios({
      url: "/clearCartByUn",
      method: "get",
      params: {
        username: state.username
      },
    }).then((res) => {
      if (res.data.code == 200) {
        ElNotification({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        loattaba(state)
        getorder(state)
      } else {
        ElNotification({
          title: "失败",
          message: "删除失败",
          type: "error",
          duration: 2000,
        });
      }
    });
  }
  return {
    clearCartByUn
  }
}
//下单
function xiadan(state) {
  const xiadan = () => {
    if (state.form.region == '') {
      ElNotification({
        title: "提示",
        message: "请选择地址",
        type: "error",
        duration: 2000,
      });
    } else {
      // console.log(this.state.form.region);
      axios({
        url: "/addOrder",
        method: "get",
        params: {
          aid: state.form.region,
          t: '2',
          username: state.username
        },
      }).then((res) => {
        // console.log(res.data);
        if (res.data.code == 200) {
          ElNotification({
            title: "成功",
            message: "下单成功",
            type: "success",
            duration: 2000,
          });
          loattaba(state)
          getorder(state)
          window.location.href="/order"
        } else {
          ElNotification({
            title: "失败",
            message: "下单失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    }
  }
  return {
    xiadan
  }
}

export default defineComponent({
  inject: ["reload"],
  setup() {

    const address = ref(false);


    const clearCartByUn1 = ref(false);
    const handleClose = (done) => {
      ElMessageBox.confirm("你确定要离开此页面吗")
        .then(() => {
          done();
        })
        .catch(() => {
          // catch error
        });
    };


    const state = reactive({
      moneys: 0,
      tabledata: [],
      tabledata1: [],
      tabledata2: [],
      username: JSON.parse(sessionStorage.getItem("token")),
      address: false,
      form: {
        region: '',
      },
    });
    onMounted(() => {
      loattaba(state);
    });
    const { proxy } = getCurrentInstance();

    return {
      ...handleChange(state),
      ...handleDelete(state),
      ...handleDelete2(state),
      ...getorder(state),
      ...toRefs(state),
      ...clearCart(state),
      ...xiadan(state),

      state,
      proxy,
      clearCartByUn1,
      handleClose,
    };
  },
  data() {
    const dialogTableVisible = ref(false);
    if (sessionStorage.getItem("token") == null) {
      ElNotification({
        title: "提示",
        message: "请先登录",
        type: "error",
        duration: 2000,
      });
      // this.$router.go(0);
      this.$router.push({
        path: "/",
      });

      // this.$router.replace("/")
    }
    const nonull = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    return {
      dialogTableVisible: false,
      addressfrom: {
        name: '',
        phone: '',
        detail: '',
        username: JSON.parse(sessionStorage.getItem("token")),
      },
      rules: {
        name: [{ validator: nonull, trigger: "blur" }],
        phone: [{ validator: nonull, trigger: "blur" }],
        detail: [{ validator: nonull, trigger: "blur" }],

      },
    };
  },
  methods: {
    dialogTableVisi() {

      this.dialogTableVisible = true

    },

    currentSel(selval) {
      console.log(selval);
    },

    address() {

    },

    addaddress(from) {

      this.$refs[from].validate((valid) => {
        if (valid) {

          var param = this.addressfrom;
          // var param = param)
          console.log(this.addressfrom)

          axios({
            url: "/userAddressAdd",
            method: "get",
            params: {
              username: param.username,
              name: param.name,
              phone: param.phone,
              detail: param.detail,
            },
          }).then((res) => {
            console.log(res.data);
            if (res.data.code == 200) {
              ElNotification({
                title: "成功",
                message: "添加成功",
                type: "success",
                duration: 2000,
              });
              this.reload();
            } else {
              ElNotification({
                title: "失败",
                message: "添加失败",
                type: "error",
                duration: 2000,
              });
            }
          });

        } else {
          ElNotification({
            title: "提示",
            message: "请输入正确的格式",
            type: "error",
            duration: 2000,
          });
          return false;
        }
        return true;
      });
    }
  },
});
</script>

<style>
#shopping {
  width: 80%;

  margin: 100px 0 100px auto;
}
.divcart {
  float: right;
  margin: 50px 250px;
}
</style>
